package jp.sourceforge.talisman.csvio.builder;

/*
 * $Id: NoQuoteCsvLineBuilder.java,v 1.1 2009/09/12 05:06:11 weiwei Exp $
 */

import java.util.ArrayList;
import java.util.List;

import jp.sourceforge.talisman.csvio.CsvIOSetting;
import jp.sourceforge.talisman.csvio.EscapeMode;

/**
 * 
 * @author Haruaki Tamada
 * @version $Revision: 1.1 $ $Date: 2009/09/12 05:06:11 $
 */
class NoQuoteCsvLineBuilder extends AbstractCsvLineBuilder{
    public NoQuoteCsvLineBuilder(){
    }

    public NoQuoteCsvLineBuilder(CsvIOSetting setting){
        super(setting);
    }

    @Override
    protected List<String> splitToTokens(String line){
        String[] tokens = line.split(",");
        CsvIOSetting setting = getSetting();

        List<String> list = new ArrayList<String>(tokens.length);
        for(String token: tokens){
            list.add(normalize(token, setting));
        }

        return list;
    }

    private String normalize(String token, CsvIOSetting setting){
        EscapeMode mode = setting.getEscapeMode();
        char qb = setting.getQuoteBegin();
        char qe = setting.getQuoteEnd();
        if(mode == EscapeMode.DOUBLE_CHARACTER){
            token.replaceAll("" + qb + qb, String.valueOf(qb));
            token.replaceAll("" + qe + qe, String.valueOf(qe));
        }
        else{
            char ec = setting.getEscapeCharacter();
            token.replaceAll("" + ec + qb, String.valueOf(qb));
            token.replaceAll("" + ec + qe, String.valueOf(qe));
            token.replaceAll("" + ec + ec, String.valueOf(ec));
        }

        return token;
    }
}
